package com.dq.jingran.exception;

import com.alibaba.fastjson.JSON;
import com.dq.jingran.entity.JrUser;
import com.dq.jingran.service.JrUserService;
import com.dq.jingran.utils.UserThreadLocal;
import com.dq.jingran.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @project: jingran
 * @ClassName: LoginHandler
 * @author: dq
 * @creat: 2022/10/9 8:19
 */
@Component
@Slf4j
public class LoginHandler implements HandlerInterceptor {

    @Autowired
    private JrUserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }


        String auth = request.getHeader("auth");
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", auth);
        log.info("=========================================================");

        if (StringUtils.isEmpty(auth)){
            R error = R.error("无请求头");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(error));
            return false;
        }

        JrUser jrUser = userService.checkTokenAndReturnData(auth);
        if (jrUser ==null){
            R error = R.error("请求头error");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(error));
            return false ;
        }

        log.info("走了线程池");
        UserThreadLocal.put(jrUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.delete();
    }
}
